package vn.vfriends.vbox.rest.reader;

import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.json.Json; 
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.ws.rs.Consumes;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.vbox.model.File;

/**
 *
 * @author tuancn
 */
@Provider
@Consumes(MediaType.APPLICATION_JSON)
public class ListFileReader implements MessageBodyReader<List<File>> {

    private static final Logger logger = LoggerFactory.getLogger(ListFileReader.class);
    
    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return type == List.class;
    }

    @Override
    public List<File> readFrom(Class<List<File>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
        List<File> files = new ArrayList<>();
        JsonReader jsonReader = Json.createReader(entityStream);
        JsonObject jsonObject = jsonReader.readObject();
        
        if(jsonObject.containsKey("contents")) {    //  Dropbox
            JsonArray array = jsonObject.getJsonArray("contents");
            Iterator<JsonValue> iterator = array.iterator();
            SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
            while(iterator.hasNext()) {
                JsonObject object = (JsonObject)iterator.next();
                File file = new File();
                
                String path = object.getString("path");
                //  id
                file.setFileId(path);
                //  name
                String[] arr = path.split("/");
                file.setName(arr[arr.length - 1]);
                //  isFolder & mimeType
                if(object.containsKey("is_dir") && object.getBoolean("is_dir")) {
                    file.setFolder(true);
                } else {
                    file.setMimeType(object.getString("mime_type"));
                }
                //  size
                file.setSize(object.getInt("bytes"));
                //  modifiedDate
                try {
                    file.setModifiedDate(formatter.parse(object.getString("modified")));
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                
                files.add(file);
            }
        } else if(jsonObject.containsKey("items")) { //  Google Drive
            JsonArray array = jsonObject.getJsonArray("items");
            Iterator<JsonValue> iterator = array.iterator();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            while(iterator.hasNext()) {
                JsonObject object = (JsonObject)iterator.next();
                File file = new File();
                //  id
                file.setFileId(object.getString("id"));
                //  name
                file.setName(object.getString("title"));
                //  isFolder & mimeType
                String mimeType = object.getString("mimeType");
                if(mimeType.equals("application/vnd.google-apps.folder")) {
                    file.setFolder(true);
                } else {
                    file.setMimeType(mimeType);
                }
                //  size
                if(object.containsKey("fileSize")) {
                    file.setSize(Long.valueOf(object.getString("fileSize")));
                } else {
                    file.setSize(0);
                }
                //  modifiedDate
                try {
                    file.setModifiedDate(formatter.parse(object.getString("modifiedDate")));
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
                
                files.add(file);
            }
        }
        jsonReader.close();
        return files;
    }
}
